package scenic;

import java.awt.Rectangle;

/**
 * This class contains utility methods.
 */
public class Util {
	/**
	 * Combines the given rectangle with the given point. The given 
	 * rectangle is modified so that it includes the given point.
	 * 
	 * @param a the rectangle.
	 * @param x the x coordinate of the point
	 * @param y the y coodrinate of the point
	 */
	public static void combine(Rectangle a, int x, int y) {
		if(a.width == 0) {
			a.x = x;
			a.y = y;
			a.width = 1;
			a.height = 1;
			return;
		}
		int oldx = a.x;
		int oldy = a.y;

		a.x = Math.min(a.x, x);
		a.y = Math.min(a.y, y);
		a.width = Math.max(oldx + a.width, x + 1) - a.x;
		a.height = Math.max(oldy + a.height, y + 1) - a.y;
	}
	
	/**
	 * Combines the two rectangles. The rectangle a is modified
	 * so that it contains the are defined by rectangle b.
	 * 
	 * @param a the first rectangle.
	 * @param b the second rectangle.
	 */
	public static void combine(Rectangle a, Rectangle b) {
		if(a.width == 0) {
			a.x = b.x;
			a.y = b.y;
			a.width = b.width;
			a.height = b.height;
			return;
		}
		int oldx = a.x;
		int oldy = a.y;

		a.x = Math.min(a.x, b.x);
		a.y = Math.min(a.y, b.y);
		a.width = Math.max(oldx + a.width, b.x + b.width) - a.x;
		a.height = Math.max(oldy + a.height, b.y + b.height) - a.y;
	}
	
	/**
	 * Calculates the common area shared by the rectangles. 
	 * The rectangle a is modified so that it contains the 
	 * common area of the two rectangles. The common area
	 * is the largest rectangle that is inside the two
	 * rectangles.
	 * 
	 * @param a the first rectangle.
	 * @param b the second rectangle.
	 */
	public static void common(Rectangle a, Rectangle b) {
		int oldx = a.x;
		int oldy = a.y;

		a.x = Math.max(a.x, b.x);
		a.y = Math.max(a.y, b.y);
		a.width = Math.min(oldx + a.width, b.x + b.width) - a.x;
		a.height = Math.min(oldy + a.height, b.y + b.height) - a.y;
	}
	
	public static boolean hasCommonArea(Rectangle a, Rectangle b) {
		return b.x < a.x + a.width && b.y < a.y + a.height &&
			a.x < b.x + b.width && a.y < b.y + b.height;
	}
	
	/**
	 * Returns a power of two that is larger or equal to the given value.
	 * Power of two is a value of the form 2^n, where n is any integer >= 0.
	 * So, for example, for the value 30 this method would return 32.
	 * 
	 * @param size the value.
	 * @return the power of two.
	 */
	public static int toPowerOfTwo(int size) {
		int s = 1;
		
		if(size == 0)
			return 0;
		while(s < size)
			s *= 2;
		return s;
	}	
}
